﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Newtonsoft.Json;
using System.Configuration;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using Microsoft.JScript;


namespace TradeWeb.Controllers
{
    public class AuditListController : Controller
    {
        //审批列表
        public dynamic GetAuditList(string strUserCode)
        {
            string jsonResult = string.Empty;

            string strENTableName = "V_Message";
            string strWhere = "UIName='列表' AND ModuleName in (select modulename from t_modulelist where ISAudit='是')";
            string strSQL = "SELECT (SELECT top 1 SortID from t_grouplist where modulename=T_ModuleCustomUI.modulename) GroupSortID,(SELECT top 1 SortID from t_Modulelist where modulename=T_ModuleCustomUI.modulename) ModuleSortID,(SELECT top 1 ENTableName from t_moduletables where modulename=T_ModuleCustomUI.modulename order by sortid) MasterTableName,ModuleName,MasterViewPK,MasterViewName FROM T_ModuleCustomUI WHERE " + strWhere;
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            SqlCommand sqlCom;
            SqlDataAdapter sqlDA;
            DataSet dsModuleNameList = new DataSet();
            try
            {
                #region 第1步：获取模块集合（数据集）

                sqlConn.Open();
                sqlCom = new SqlCommand(strSQL, sqlConn);
                sqlDA = new SqlDataAdapter(sqlCom);
                sqlDA.Fill(dsModuleNameList);
                dsModuleNameList.Tables[0].DefaultView.Sort = "GroupSortID,ModuleSortID";

                List<string> lstStrSQL = new List<string>();
                List<string> lstTableName = new List<string>();
                int iTableName = 0;
                foreach (DataRowView drv in dsModuleNameList.Tables[0].DefaultView)
                {
                    string strModuleName = drv["ModuleName"].ToString();
                    string strMasterViewName = drv["MasterViewName"].ToString();
                    string strPKColName = drv["MasterViewPK"].ToString();
                    string strMasterTable = drv["MasterTableName"].ToString();
                    string strAuditTable = drv["MasterTableName"].ToString() + "Audit";
                    int iGroupSortID = drv["GroupSortID"] == DBNull.Value ? 0 : (int)drv["GroupSortID"];
                    int iModuleSortID = drv["ModuleSortID"] == DBNull.Value ? 0 : (int)drv["ModuleSortID"];
                    string strSQLString = "select '" + strModuleName + "' ModuleName," + strMasterViewName + ".CNUserName," + strMasterViewName + "." + strPKColName + " PKValue," + iGroupSortID.ToString() + " GroupSortID," + iModuleSortID.ToString() + " ModuleSortID from " + strMasterViewName + " LEFT OUTER JOIN "
                        + strAuditTable + " ON " + strMasterViewName + "." + strPKColName + "=" + strAuditTable + "." + strPKColName + " AND " + strMasterViewName + ".ISDel=" + strAuditTable + ".ISDel where " + strMasterViewName + ".ISDel=0 AND " + strMasterViewName + ".SendAuditState=1 AND " + strAuditTable + ".AuditState=0 AND (CAST("
                        + strAuditTable + ".WaitAuditer as varchar(500))='" + strUserCode + "' or " + strAuditTable + ".WaitAuditer like '%|" + strUserCode + "%' or " + strAuditTable + ".WaitAuditer like '%"
                        + strUserCode + "|%')  AND ISNULL((select top 1 AuditState from " + strAuditTable + " as Audit where ISDel=0 AND Audit." + strPKColName + "=" + strMasterViewName + "." + strPKColName + " AND Audit.SortID<" + strAuditTable + ".SortID order by SortID desc),1) =1";
                    iTableName++;
                    string strENTableNameTemp = strENTableName + iTableName.ToString();

                    //查询语句集
                    lstStrSQL.Add(strSQLString);
                    //查询结果集－数据集表名
                    lstTableName.Add(strENTableNameTemp);
                }
                #endregion

                #region 第2步：获取所有模块审批消息提醒集合（数据集）

                DataSet dsMessage = new DataSet();
                SqlDataAdapter sqlAdaMsg;
                List<SqlDataAdapter> sqlAdaListMsg = new List<SqlDataAdapter>();
                string strSQLMsg;
                string strTableNameMsg;

                for (int i = 0; i < lstTableName.Count; i++)
                {
                    strSQLMsg = lstStrSQL[i];
                    strTableNameMsg = lstTableName[i];
                    sqlAdaMsg = new SqlDataAdapter(strSQLMsg, sqlConn);
                    sqlAdaMsg.Fill(dsMessage, strTableNameMsg);

                    #region 主键赋上默认值
                    if (dsMessage.Tables[strTableNameMsg].PrimaryKey != null)
                    {
                        foreach (DataColumn dc in dsMessage.Tables[strTableNameMsg].PrimaryKey)
                        {
                            if (dc.ReadOnly) continue;
                            Type colType = dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DataType;
                            if (colType == System.Type.GetType("System.String"))
                            {
                                dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = string.Empty;
                            }
                            else
                            {
                                if (colType == System.Type.GetType("System.Int16") || colType == System.Type.GetType("System.Int32") ||
                                   colType == System.Type.GetType("System.Int64") || colType == System.Type.GetType("System.Single") ||
                                   colType == System.Type.GetType("System.UInt16") || colType == System.Type.GetType("System.UInt32") ||
                                   colType == System.Type.GetType("System.UInt64") || colType == System.Type.GetType("System.Decimal") ||
                                   colType == System.Type.GetType("System.Double"))
                                {
                                    dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = 0;
                                }
                                else
                                {
                                    if (colType == System.Type.GetType("System.DateTime"))
                                    {
                                        dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = DateTime.Now;
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                #region 第3步：结果数据集
                string strTrueENTableName = string.Empty;
                List<string> lstModuleNameResult = new List<string>();
                List<int> indexModuleNameList = new List<int>();
                DataSet dsResult = new DataSet();
                foreach (DataTable dt in dsMessage.Tables)
                {
                    if (dt.TableName.StartsWith(strENTableName))
                    {
                        if (dt.DefaultView.Count > 0)
                        {
                            if (lstModuleNameResult.IndexOf(dt.DefaultView[0]["ModuleName"].ToString()) < 0)
                            {
                                lstModuleNameResult.Add(dt.DefaultView[0]["ModuleName"].ToString());
                                indexModuleNameList.Add(dt.DefaultView.Count);
                            }
                        }
                        if (strTrueENTableName == string.Empty)
                        {
                            dsResult.Tables.Add(dt.Copy());
                            strTrueENTableName = dt.TableName;
                        }
                        else
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                dsResult.Tables[strTrueENTableName].Rows.Add(dr.ItemArray);
                            }
                        }
                    }
                }
                if (strTrueENTableName != string.Empty)
                {
                    DataColumn dc = new DataColumn("MessageText", System.Type.GetType("System.String"));
                    dc.Expression = "ISNULL(CNUserName,'')+'的'+isnull(ModuleName,'')+isnull(PKValue,'')+'需要您审批，请查看！'";
                    dsResult.Tables[strTrueENTableName].Columns.Add(dc);
                    dsResult.Tables[strTrueENTableName].DefaultView.Sort = "GroupSortID,ModuleSortID";
                }
                #endregion

                sqlConn.Close();
                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
            catch (Exception ex)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
            return jsonResult;
        }
        //审批消息－－数目
        public dynamic GetAuditCount(string strUserCode)
        {
            string jsonResult = string.Empty;

            string strENTableName = "V_Message";
            string strWhere = "UIName='列表' AND ModuleName in (select modulename from t_modulelist where ISAudit='是')";
            string strSQL = "SELECT (SELECT top 1 SortID from t_grouplist where modulename=T_ModuleCustomUI.modulename) GroupSortID,(SELECT top 1 SortID from t_Modulelist where modulename=T_ModuleCustomUI.modulename) ModuleSortID,(SELECT top 1 ENTableName from t_moduletables where modulename=T_ModuleCustomUI.modulename order by sortid) MasterTableName,ModuleName,MasterViewPK,MasterViewName FROM T_ModuleCustomUI WHERE " + strWhere;
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            SqlCommand sqlCom;
            SqlDataAdapter sqlDA;
            DataSet dsModuleNameList = new DataSet();
            try
            {
                #region 第1步：获取模块集合（数据集）

                sqlConn.Open();
                sqlCom = new SqlCommand(strSQL, sqlConn);
                sqlDA = new SqlDataAdapter(sqlCom);
                sqlDA.Fill(dsModuleNameList);
                dsModuleNameList.Tables[0].DefaultView.Sort = "GroupSortID,ModuleSortID";

                List<string> lstStrSQL = new List<string>();
                List<string> lstTableName = new List<string>();
                int iTableName = 0;
                foreach (DataRowView drv in dsModuleNameList.Tables[0].DefaultView)
                {
                    string strModuleName = drv["ModuleName"].ToString();
                    string strMasterViewName = drv["MasterViewName"].ToString();
                    string strPKColName = drv["MasterViewPK"].ToString();
                    string strMasterTable = drv["MasterTableName"].ToString();
                    string strAuditTable = drv["MasterTableName"].ToString() + "Audit";
                    int iGroupSortID = drv["GroupSortID"] == DBNull.Value ? 0 : (int)drv["GroupSortID"];
                    int iModuleSortID = drv["ModuleSortID"] == DBNull.Value ? 0 : (int)drv["ModuleSortID"];
                    string strSQLString = "select '" + strModuleName + "' ModuleName," + strMasterViewName + ".CNUserName," + strMasterViewName + "." + strPKColName + " PKValue," + iGroupSortID.ToString() + " GroupSortID," + iModuleSortID.ToString() + " ModuleSortID from " + strMasterViewName + " LEFT OUTER JOIN "
                        + strAuditTable + " ON " + strMasterViewName + "." + strPKColName + "=" + strAuditTable + "." + strPKColName + " AND " + strMasterViewName + ".ISDel=" + strAuditTable + ".ISDel where " + strMasterViewName + ".ISDel=0 AND " + strMasterViewName + ".SendAuditState=1 AND " + strAuditTable + ".AuditState=0 AND (CAST("
                        + strAuditTable + ".WaitAuditer as varchar(500))='" + strUserCode + "' or " + strAuditTable + ".WaitAuditer like '%|" + strUserCode + "%' or " + strAuditTable + ".WaitAuditer like '%"
                        + strUserCode + "|%')  AND ISNULL((select top 1 AuditState from " + strAuditTable + " as Audit where ISDel=0 AND Audit." + strPKColName + "=" + strMasterViewName + "." + strPKColName + " AND Audit.SortID<" + strAuditTable + ".SortID order by SortID desc),1) =1";
                    iTableName++;
                    string strENTableNameTemp = strENTableName + iTableName.ToString();

                    //查询语句集
                    lstStrSQL.Add(strSQLString);
                    //查询结果集－数据集表名
                    lstTableName.Add(strENTableNameTemp);
                }
                #endregion

                #region 第2步：获取所有模块审批消息提醒集合（数据集）

                DataSet dsMessage = new DataSet();
                SqlDataAdapter sqlAdaMsg;
                List<SqlDataAdapter> sqlAdaListMsg = new List<SqlDataAdapter>();
                string strSQLMsg;
                string strTableNameMsg;

                for (int i = 0; i < lstTableName.Count; i++)
                {
                    strSQLMsg = lstStrSQL[i];
                    strTableNameMsg = lstTableName[i];
                    sqlAdaMsg = new SqlDataAdapter(strSQLMsg, sqlConn);
                    sqlAdaMsg.Fill(dsMessage, strTableNameMsg);

                    #region 主键赋上默认值
                    if (dsMessage.Tables[strTableNameMsg].PrimaryKey != null)
                    {
                        foreach (DataColumn dc in dsMessage.Tables[strTableNameMsg].PrimaryKey)
                        {
                            if (dc.ReadOnly) continue;
                            Type colType = dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DataType;
                            if (colType == System.Type.GetType("System.String"))
                            {
                                dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = string.Empty;
                            }
                            else
                            {
                                if (colType == System.Type.GetType("System.Int16") || colType == System.Type.GetType("System.Int32") ||
                                   colType == System.Type.GetType("System.Int64") || colType == System.Type.GetType("System.Single") ||
                                   colType == System.Type.GetType("System.UInt16") || colType == System.Type.GetType("System.UInt32") ||
                                   colType == System.Type.GetType("System.UInt64") || colType == System.Type.GetType("System.Decimal") ||
                                   colType == System.Type.GetType("System.Double"))
                                {
                                    dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = 0;
                                }
                                else
                                {
                                    if (colType == System.Type.GetType("System.DateTime"))
                                    {
                                        dsMessage.Tables[strTableNameMsg].Columns[dc.ColumnName].DefaultValue = DateTime.Now;
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                #region 第3步：结果数据集
                string strTrueENTableName = string.Empty;
                List<string> lstModuleNameResult = new List<string>();
                List<int> indexModuleNameList = new List<int>();
                DataSet dsResult = new DataSet();
                foreach (DataTable dt in dsMessage.Tables)
                {
                    if (dt.TableName.StartsWith(strENTableName))
                    {
                        if (dt.DefaultView.Count > 0)
                        {
                            if (lstModuleNameResult.IndexOf(dt.DefaultView[0]["ModuleName"].ToString()) < 0)
                            {
                                lstModuleNameResult.Add(dt.DefaultView[0]["ModuleName"].ToString());
                                indexModuleNameList.Add(dt.DefaultView.Count);
                            }
                        }
                        if (strTrueENTableName == string.Empty)
                        {
                            dsResult.Tables.Add(dt.Copy());
                            strTrueENTableName = dt.TableName;
                        }
                        else
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                dsResult.Tables[strTrueENTableName].Rows.Add(dr.ItemArray);
                            }
                        }
                    }
                }
                #endregion

                sqlConn.Close();
                int iCount = 0;
                if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                {
                    iCount = (int)dsResult.Tables[0].Rows.Count;
                }
                jsonResult = "{\"success\":true  ,\"data\":" + "[{\"Count\":\"" + iCount + "\"}]" + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
            catch (Exception ex)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
            return jsonResult;
        }

        //获取审批页面详细信息          [修改处：审批预览(打印模板)、审批信息两个模块可以复用；基本信息、产品列表要自己确定；]
        public string GetAudit(string strModuleName, string strPKValue,string strUserCode)
        {
            string jsonResult = string.Empty;
            //取到模块名
            string _strModuleName = Microsoft.JScript.GlobalObject.decodeURIComponent(strModuleName);
            string _strMasterPKValue=strPKValue;

            string _strMasterTableName = string.Empty;
            string _strMasterPKName = string.Empty;
            
            //打印格式、审批流程可以模块复用；
            string _strPrintTableName=string.Empty;
            string _strAuditTableName=string.Empty;
            
            List<string> lstSQL = new List<string>();
            List<string> lstTableName = new List<string>();
            string strSQL = string.Empty;
            string strTableName = string.Empty;
            switch (_strModuleName)
            {
                case "外销合同":
                    {
                        #region 外销合同
                        _strMasterTableName = "T_ExpPact";
                        _strMasterPKName    = "PactNum";
                        _strPrintTableName  = "T_ExpPactPrint";
                        _strAuditTableName  = "T_ExpPactAudit";

                        //基本信息
                        strSQL = "select aa.PactNum,aa.SaveTime,aa.PactDate,aa.CNUserName,aa.UserCode,aa.Creater,aa.CreaterName,aa.ClientCode,bb.ClientName,aa.LastShip,aa.PriceClause,aa.Curr,aa.Payment,aa.ExportPort,aa.AimPort,aa.SendAuditState,aa.TotalSaleMoney from (select * from T_ExpPact where isdel=0) aa JOIN (SELECT * FROM  dbo.T_Client WHERE ISDel=0) bb ON aa.ClientCode =bb.ClientCode where aa.PactNum='"+_strMasterPKValue+"'";
                        strTableName = "T_ExpPact";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //产品列表
                        strSQL = "select PactNum,CNProductName,CNProductSpec,Color,Quantity,SalePrice,MoneyS,StockCurr,CNUnit,ENUnits from (select * from T_ExpPactProduct where isdel=0) aa where aa.PactNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ExpPactProduct";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //成本核算------不可复用
                        strSQL = "select Curr1,TotalSaleMoney,RMBTotalSaleMoney,Curr2,Commission,RMBTotalCharge,RMBCommission,Curr8,StockMoney,RMBStockMoney,Curr9,DrawBackMoney,RMBDrawBackMoney,Curr4,SeaFreight,Curr5,SeaFreight1,Curr6,BankFreight,GrossProfit,TotalProfit,ProfitRate,ExportCost,NetaExportCost  from (select * from T_ExpPactAccount where isdel=0) aa where aa.PactNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ExpPactAccount";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批预览[打印模板]与审批信息可以复用（不用做任何修改）
                        #region 打印格式与审批流程可以复用；

                        //审批预览[打印模板]
                        strSQL = "SELECT ModuleName,RptClass,RptName,NEWID() as RptGUID  FROM ts_Report where ( ModuleName = '"+_strModuleName+"') AND charindex('" + strUserCode + "|' ,AllowReader)>0  and isdel=0 and rptClass='Excel'";
                        strTableName = _strPrintTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批信息--[一定要记得按审批流程依次排序]
                        strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,(Select top 1 CNUserName from T_User Where T_User.IsDel=0 And T_User.UserCode = bb.WaitAuditer) as CNUserName,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                            + "JOIN (SELECT * FROM "+_strAuditTableName+" WHERE isdel=0) bb  ON aa."+_strMasterPKName+"=bb."+_strMasterPKName+" WHERE aa."+_strMasterPKName+"='" + _strMasterPKValue + "'  ORDER BY bb.SortID ASC";
                        strTableName = _strAuditTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);
                        #endregion
                        
                        #endregion
                    }
                    break;
                case "销售报价":
                    {
                        #region 销售报价

                        _strMasterTableName = "T_ExpQuote";
                        _strMasterPKName = "QuoteNum";
                        _strPrintTableName = "T_ExpQuotePrint";
                        _strAuditTableName = "T_ExpQuoteAudit";

                        //基本信息
                        strSQL = "select aa.QuoteNum,SaveTime,QuoteDate,UserCode,CNUserName,aa.Creater,aa.CreaterName,SendAuditState,ClientCode,bb.ClientName,PriceClause,Payment,AimPort,ExportPort,Curr,TotalSaleMoney from (select * from T_ExpQuote where isdel=0) aa join (select * from T_ExpQuoteContactInfo where isdel=0) bb on aa.QuoteNum=bb.QuoteNum  where aa.QuoteNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ExpQuote";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //产品列表
                        strSQL = "select SerialID,QuoteNum,ProductCode,CNProductName,ENProductName,CNProductSpec,Color,Quantity,ENUnits,SalePrice,Moneys,FactoryNameFace,StockCurr,RMBStockPrice,DrawbackMoney,LRL,Remark from (select * from T_ExpQuoteProduct where isdel=0) aa where aa.QuoteNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ExpQuoteProduct";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批预览[打印模板]与审批信息可以复用（不用做任何修改）
                        #region 打印格式与审批流程可以复用；

                        //审批预览[打印模板]
                        strSQL = "SELECT ModuleName,RptClass,RptName,NEWID() as RptGUID  FROM ts_Report where ( ModuleName = '" + _strModuleName + "') AND charindex('" + strUserCode + "|' ,AllowReader)>0  and isdel=0 and rptClass='Excel'";
                        strTableName = _strPrintTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批信息--[一定要记得按审批流程依次排序]
                        strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,(Select top 1 CNUserName from T_User Where T_User.IsDel=0 And T_User.UserCode = bb.WaitAuditer) as CNUserName,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                            + "JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "'  ORDER BY bb.SortID ASC";
                        strTableName = _strAuditTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);
                        #endregion

                        #endregion
                    }
                    break;
                case "采购合同":
                    {
                        #region 采购合同

                        _strMasterTableName = "T_StockPact";
                        _strMasterPKName = "PactNum";
                        _strPrintTableName = "T_StockPactPrint";
                        _strAuditTableName = "T_StockPactAudit";

                        //基本信息
                        strSQL = "select aa.PactNum,SaveTime,PactDate,ConsignmentDate,aa.Creater,aa.CreaterName,CNUserName,UserCode,ExpPactNums,SendAuditState,ClientCode,bb.ClientName,PayCondation,Curr,TotalSaleMoney  from (select * from T_StockPact where isdel=0) aa join (select * from T_StockPactContactInfo where isdel=0) bb on aa.PactNum=bb.PactNum  where aa.PactNum='" + _strMasterPKValue + "'";
                        strTableName = "T_StockPact";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //产品列表
                        strSQL = "select PactNum,ExpPactNum,(select RMBRate from T_exppact tab0 where tab0.PactNum=aa.ExpPactNum) as ItemRMBRate"
                        + ",(select SalePrice from T_exppactProduct tab1 where tab1.isDel=0 and  tab1.GUID=aa.ExpPactGUID and tab1.PactNum=aa.ExpPactNum) as ItemSalePrice "
                        + ",(select MoneyS from T_exppactProduct tab2 where tab2.isDel=0 and tab2.GUID=aa.ExpPactGUID and tab2.PactNum=aa.ExpPactNum) as  ItemSaleMoneyS "
                        + ",(select DrawbackVAT from T_exppactProduct tab3 where tab3.isDel=0 and tab3.GUID=aa.ExpPactGUID and tab3.PactNum=aa.ExpPactNum) as ItemSaleDrawbackVAT "
                        + ",0 as ItemDrawBackMoney, 0 as ItemProfitMoney,0 as ItemProfitRate, 0 as ItemExpertCost "
                        + ",ProductCode,CustProductCode,CustGoodsCode,FactoryProductCode,ExpPactNum,CNProductName,ENProductName,Model,"
                        + "CNProductSpec,Color,Quantity,CNUnit,StockPrice,Moneys,SaleCurr,SalePrice,DrawbackMoney "
                        + " from (select * from T_StockPactProduct where isdel=0) aa where aa.PactNum='" + strPKValue + "'";
                        strTableName = "T_StockPactProduct";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批预览[打印模板]与审批信息可以复用（不用做任何修改）
                        #region 打印格式与审批流程可以复用；

                        //审批预览[打印模板]
                        strSQL = "SELECT ModuleName,RptClass,RptName,NEWID() as RptGUID  FROM ts_Report where ( ModuleName = '" + _strModuleName + "') AND charindex('" + strUserCode + "|' ,AllowReader)>0  and isdel=0 and rptClass='Excel'";
                        strTableName = _strPrintTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批信息--[一定要记得按审批流程依次排序]
                        strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,(Select top 1 CNUserName from T_User Where T_User.IsDel=0 And T_User.UserCode = bb.WaitAuditer) as CNUserName,aa.SendAuditState,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                            + "JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "'  ORDER BY bb.SortID ASC";
                        strTableName = _strAuditTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);
                        #endregion

                        #endregion
                    }
                    break;
                case "付款申请":
                    {
                        #region 付款申请   预付款、付费用、付货款－－－－－都共用这个方法获取数据。

                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strPrintTableName = "T_ApplyMoneyPrint";
                        _strAuditTableName = "T_ApplyMoneyAudit";

                        //基本信息
                        strSQL = "select aa.ApplyNum,SaveTime,aa.UserCode,aa.CNUserName,ApplyDate,Creater,CreaterName,ClientCode,SendAuditState,bb.ClientName,ApplyClass,CustOpenBank,CustAccounts,Remark,Curr,TotalMoneyS from (select * from T_ApplyMoney where isdel=0) aa join (select * from T_ApplyMoneyContactInfo where isdel=0) bb on aa.ApplyNum=bb.ApplyNum  where aa.ApplyNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ApplyMoney";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //产品列表
                        strSQL = "select InvoiceNum,StockPactNum,StockPactMoney,Moneys,CYMoneys,CostItem,ApplyDesc,Moneys,ApplyYFKMoneyed,FTYFMoneyed,ApplyFHKMoneyed,Remark from (select * from T_ApplyMoneyPact where isdel=0) aa where aa.ApplyNum='" + _strMasterPKValue + "'";
                        strTableName = "T_ApplyMoneyProduct";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批预览[打印模板]与审批信息可以复用（不用做任何修改）
                        #region 打印格式与审批流程可以复用；

                        //审批预览[打印模板]
                        strSQL = "SELECT ModuleName,RptClass,RptName,NEWID() as RptGUID  FROM ts_Report where ( ModuleName = '" + _strModuleName + "') AND charindex('" + strUserCode + "|' ,AllowReader)>0  and isdel=0 and rptClass='Excel'";
                        strTableName = _strPrintTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批信息--[一定要记得按审批流程依次排序]
                        strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,(Select top 1 CNUserName from T_User Where T_User.IsDel=0 And T_User.UserCode = bb.WaitAuditer) as CNUserName,aa.SendAuditState,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                            + "JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "'  ORDER BY bb.SortID ASC";
                        strTableName = _strAuditTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);
                        #endregion

                        #endregion
                    }
                    break;
                case "议付单证":
                    {
                        #region 议付单证－－这里"基本信息、产品列表"数据取视图数据（审批操作只需保持：InvoiceNum,SortID,isDel这三个条件一致即可）。
                        _strMasterTableName = "T_InvoiceDoc";
                        _strMasterPKName = "InvoiceNum";
                        _strPrintTableName = "T_InvoiceDocPrint";
                        _strAuditTableName = "T_InvoiceDocAudit";

                        //基本信息
                        strSQL = "select SaveTime,ISDel,InvoiceNum,CustPactNums,ExpPactNums,PriceClause,InvoiceDate,OpenShipDate,Creater,CreaterName,UserCode,CNUserName,ClientCode,ClientName,Payment,Curr,TotalSaleMoney,CustMoneyStatus,CustMoneyStatus1,CustMoney,NoCustMoney,AimCountry,AimPort,ExportPort,ShippingMode from V_InvoiceDOC where isDel=0 and InvoiceNum='" + _strMasterPKValue + "'";
                        strTableName = "T_InvoiceDoc";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //产品列表
                        strSQL = "select InvoiceNum,ExpPactNum,CustPactNum,ExpPactGUID,CustProductCode,ProductCode,CNProductName,ENProductName,CNProductSpec,ENProductSpec ,Quantity,QuantityUnit,SalePrice,MoneyS,Remark from T_InvoiceDOCProduct where InvoiceNum='" + _strMasterPKValue + "'";
                        strTableName = "T_InvoiceDocProduct";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //运输信息
                        strSQL = "select * from T_InvoiceDOCShipping where InvoiceNum='" + _strMasterPKValue + "'";
                        strTableName = "T_InvoiceDOCShipping";
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批预览[打印模板]与审批信息可以复用（不用做任何修改）
                        #region 打印格式与审批流程可以复用；

                        //审批预览[打印模板]
                        strSQL = "SELECT ModuleName,RptClass,RptName,NEWID() as RptGUID  FROM ts_Report where ( ModuleName = '" + _strModuleName + "') AND charindex('" + strUserCode + "|' ,AllowReader)>0  and isdel=0 and rptClass='Excel'";
                        strTableName = _strPrintTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);

                        //审批信息--[一定要记得按审批流程依次排序]
                        strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,(Select top 1 CNUserName from T_User Where T_User.IsDel=0 And T_User.UserCode = bb.WaitAuditer) as CNUserName,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                            + "JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "'  ORDER BY bb.SortID ASC";
                        strTableName = _strAuditTableName;
                        lstSQL.Add(strSQL);
                        lstTableName.Add(strTableName);
                        #endregion

                        #endregion
                    }
                    break;
                default:
                    break;
            }
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            SqlDataAdapter sqlAdapter;
            DataSet dsList = new DataSet();
            try
            {
                sqlConn.Open();
                for (int i = 0; i < lstSQL.Count; i++)
                {
                    sqlAdapter = new SqlDataAdapter(lstSQL[i], sqlConn);
                    sqlAdapter.Fill(dsList, lstTableName[i]);
                }
                sqlConn.Close();
                if (_strModuleName == "采购合同")
                {
                    #region 如果是采购合同，需要计算利润信息、成本信息；
                    if (dsList.Tables["T_StockPactProduct"].DefaultView.Count > 0) 
                    {
                        for (int i = 0; i < dsList.Tables["T_StockPactProduct"].DefaultView.Count; i++)
                        {   
                            //采购数量
                            decimal decQuantity = dsList.Tables["T_StockPactProduct"].DefaultView[i]["Quantity"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["Quantity"];
                            //采购金额
                            decimal decMoneys = dsList.Tables["T_StockPactProduct"].DefaultView[i]["Moneys"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["Moneys"];

                            //销售－兑人民币汇率
                            decimal decItemRMBRate = dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemRMBRate"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemRMBRate"];
                            //销售单价
                            decimal decItemSalePrice = dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSalePrice"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSalePrice"];
                            //销售金额
                            decimal decItemSaleMoneyS = dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSaleMoneyS"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSaleMoneyS"];
                            //销售退税率
                            decimal decItemSaleDrawbackVAT = dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSaleDrawbackVAT"] == DBNull.Value ? 0 : (decimal)dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSaleDrawbackVAT"];
                            

                            //结果：销售金额
                            decimal d_SaleMoneyS =Math.Round(decQuantity * decItemSalePrice,2) ;
                            //结果：退税收入
                            decimal d_DrawBackMoney = Math.Round((decMoneys /1.17m * decItemSaleDrawbackVAT), 2);
                            //结果：利润额
                            decimal d_ProfitMoney = Math.Round(d_SaleMoneyS * decItemRMBRate, 2) - decMoneys + d_DrawBackMoney;
                            //结果：利润率
                            decimal d_ProfitRate = Math.Round(d_ProfitMoney/d_SaleMoneyS, 2);
                            //结果：换汇成本
                            decimal d_ExpertCost = Math.Round((decMoneys-d_DrawBackMoney)/d_SaleMoneyS, 2);

                            //核算成本、利润信息
                            dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemSaleMoneyS"] = d_SaleMoneyS;
                            dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemDrawBackMoney"] = d_DrawBackMoney;
                            dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemProfitMoney"] = d_ProfitMoney;
                            dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemProfitRate"] = d_ProfitRate;
                            dsList.Tables["T_StockPactProduct"].DefaultView[i]["ItemExpertCost"] = d_ExpertCost;
                            dsList.Tables["T_StockPactProduct"].DefaultView[i].EndEdit();
                        }
                    }
                    #endregion
                }
                string strDstoJson = JsonConvert.SerializeObject(dsList);
                jsonResult = "{\"success\":true  ,\"data\":" + strDstoJson + "  ,\"message\":\"正常\"}";
            }
            catch (Exception ex)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
            return jsonResult;
        }

        //审批通过                      [修改处：Case模块名、主表名、主键名、审批表名]
        public string AuditPass(string strModuleName, string strPKValue, string strSortID, string strUserCode, string strAuditNote,string strSaveTime)
        {
            string jsonResult = string.Empty;
            //模块名、主键字段、主键值、主表名、审批表名
            string _strModuleName = string.Empty;
            string _strMasterTableName = string.Empty;
            string _strAuditTableName = string.Empty;
            string _strMasterPKName = string.Empty;
            string _strMasterPKValue = string.Empty;
            //模块名、主键值
            _strModuleName = Microsoft.JScript.GlobalObject.decodeURIComponent(strModuleName);
            _strMasterPKValue = strPKValue;

            //取出对应的表名、审批表名、主键名
            switch (_strModuleName)
            {
                case "外销合同":
                    {
                        _strMasterTableName = "T_ExpPact";
                        _strAuditTableName = "T_ExpPactAudit";
                        _strMasterPKName = "PactNum";
                    }
                    break;
                case "销售报价":
                    {
                        _strMasterTableName = "T_ExpQuote";
                        _strAuditTableName = "T_ExpQuoteAudit";
                        _strMasterPKName = "QuoteNum";
                    }
                    break;
                case "采购合同":
                    {
                        _strMasterTableName = "T_StockPact";
                        _strMasterPKName = "PactNum";
                        _strAuditTableName = "T_StockPactAudit";
                    }
                    break;
                case "预付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付费用申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付货款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付佣金申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "其他付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "议付单证":
                    {
                        _strMasterTableName = "T_InvoiceDoc";
                        _strMasterPKName = "InvoiceNum";
                        _strAuditTableName = "T_InvoiceDocAudit";
                    }
                    break;
            }
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            sqlConn.Open();
            SqlTransaction tran = null;
            try
            {
                #region 验证时间戳
                string strSQLSaveTime = "select SaveTime From " + _strMasterTableName + " Where " + _strMasterPKName + "=@" + _strMasterPKName + " and isDel=0 ";
                SqlCommand sqlComSaveTime = new SqlCommand(strSQLSaveTime, sqlConn);
                sqlComSaveTime.Parameters.Add("@" + _strMasterPKName, SqlDbType.VarChar, 50);
                sqlComSaveTime.Parameters["@" + _strMasterPKName].Value = _strMasterPKValue;

                SqlDataAdapter sqlAdaSaveTime = new SqlDataAdapter(sqlComSaveTime);
                DataSet dsSaveTime = new DataSet();
                sqlAdaSaveTime.Fill(dsSaveTime);
                if (dsSaveTime.Tables[0].DefaultView.Count == 0) 
                {
                    return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"数据记录已经不存在!\"}";
                }
                //如果记录不存在：情况是别人已删除                                  （验证、中断提交、返回消息）
                //如果记录存在：但为空，                                            （不验证，继续）
                //如果记录存在：但不为空、此客户端为空：别人已保存过，              （验证、中断提交、返回消息）
                //如果记录存在：但不为空、此客户端不为空：相同：别人未保存          （验证、继续）
                //如果记录存在：但不为空、此客户端不为空：不同：别人保存过          （验证、中断提交、返回消息）

                string strTimeClient = string.Empty;
                string strTrueSaveTime = string.Empty;

                //如果数库记录存在：且为空。不验证、继续。
                //如果数库记录存在：不为空。1、客户端无时间戳、有时间戳不一致。均提示已修改。
                if (dsSaveTime.Tables[0].DefaultView[0]["SaveTime"] != DBNull.Value)
                {
                    //取出数据库中时间
                    DateTime dtTrueSaveTime = (DateTime)dsSaveTime.Tables[0].DefaultView[0]["SaveTime"];
                    strTrueSaveTime = string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", dtTrueSaveTime);

                    strSaveTime = Microsoft.JScript.GlobalObject.decodeURIComponent(strSaveTime);
                    if (strSaveTime == "null" || string.IsNullOrEmpty(strSaveTime) || strSaveTime != strTrueSaveTime)
                    {
                        //return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"记录已经被别人修改，请重新打开！\"}";
                    }
                }
                #endregion

                //注意按审批流程排序
                string strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,aa.SendAuditDate,bb.* FROM (SELECT * FROM "+_strMasterTableName+" WHERE isdel=0) aa  JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "' ORDER BY bb.SortID ASC";
                string strTableName = "T_Audit";
                SqlDataAdapter sqlDA;
                DataSet dsAudit = new DataSet();
                sqlDA = new SqlDataAdapter(strSQL, sqlConn);
                sqlDA.Fill(dsAudit, strTableName);


                DataTable dtAudit = dsAudit.Tables[0];
                //创建者
                string strCreater = string.Empty;
                string strCreaterName = string.Empty;
                string strFlowName = string.Empty;
                string strNoticUserCode = string.Empty;

                if (dsAudit.Tables.Count > 0 && dsAudit.Tables[0].Rows.Count > 0)
                {
                    strCreater = dtAudit.Rows[0]["Creater"].ToString();
                    strCreaterName = dtAudit.Rows[0]["CreaterName"].ToString();
                    strFlowName = dtAudit.Rows[0]["FlowName"].ToString();
                }
                #region 发送消息的3种情况：2种操作

                //1、单流程                 通知Creater           A、最终流程      strStatus = 100
                //2、多流程非最后流程       通知下一流程          B、非最终流程    strStatus = 10;
                //3、多流程最后流程         通知Creater           A、最终流程      strStatus = 100
                int strStatus = -1;

                if (dtAudit != null && dsAudit.Tables[0].Rows.Count > 0)
                {
                    dtAudit.DefaultView.Sort = "SortID ASC";
                    int maxSortID = (int)dtAudit.Rows[dtAudit.Rows.Count - 1]["SortID"];
                    //1、单流程     2、多流程－最后一道流程；
                    if (dtAudit.Rows.Count == 1 || (dtAudit.Rows.Count > 1 && strSortID == maxSortID.ToString()))
                    {
                        strNoticUserCode = dtAudit.Rows[0]["Creater"].ToString();
                        strStatus = 100;
                    }
                    //2、多流程非最后一道流程；
                    else if (dtAudit.Rows.Count > 1 && strSortID != maxSortID.ToString())
                    {
                        int rowNum = -1;
                        for (int i = 0; i < dtAudit.DefaultView.Count; i++)
                        {
                            string strSort = dtAudit.DefaultView[i]["SortID"].ToString();
                            if (strSort == strSortID)
                            {
                                rowNum = i;
                            }
                        }
                        if (rowNum >= 0)
                        {
                            strNoticUserCode = dtAudit.DefaultView[rowNum + 1]["WaitAuditer"].ToString();
                            strStatus = 10;
                        }
                    }
                }
                #endregion

                //审批通过：审批表状态更新为1。主表状态更新为：[最后一个流程：2][非最后流程：1]
                int stateAuditAuditState = 1;
                int stateMasterAuditState =1;
                if (strStatus==100) 
                {
                     stateMasterAuditState = 2;
                }
                else if (strStatus ==10)
                {
                     stateMasterAuditState = 1;
                }

                #region 审批处理的事务：更新审批表、主表、清除消息、发送消息

                tran = sqlConn.BeginTransaction();
                //修改审批表
                string strSQLUpAudit = "Update "+_strAuditTableName+" Set AuditState=@AuditState ,Auditer=@Auditer ,AuditDate=getdate(),AuditNote=@AuditNote where isDel=0 and "+_strMasterPKName+"=@"+_strMasterPKName+" and SortID=@SortID";
                SqlCommand sqlComUpAduit = new SqlCommand(strSQLUpAudit, sqlConn);
                sqlComUpAduit.Parameters.Add("@AuditState", SqlDbType.Int);
                sqlComUpAduit.Parameters["@AuditState"].Value = stateAuditAuditState;
                sqlComUpAduit.Parameters.Add("@Auditer", SqlDbType.VarChar, 50);
                sqlComUpAduit.Parameters["@Auditer"].Value = strUserCode;
                sqlComUpAduit.Parameters.Add("@AuditNote", SqlDbType.Text);
                sqlComUpAduit.Parameters["@AuditNote"].Value = strAuditNote.Trim();
                sqlComUpAduit.Parameters.Add("@" + _strMasterPKName, SqlDbType.VarChar, 100);
                sqlComUpAduit.Parameters["@" + _strMasterPKName].Value = strPKValue;
                sqlComUpAduit.Parameters.Add("@SortID", SqlDbType.Int);
                sqlComUpAduit.Parameters["@SortID"].Value = strSortID;
                sqlComUpAduit.Transaction = tran;
                sqlComUpAduit.ExecuteNonQuery();
                //修改主表
                string strSQLUpMaster = "Update " + _strMasterTableName + " set SaveTime=getDate(),AuditState=" + stateMasterAuditState + " where isDel=0 and " + _strMasterPKName + "=@" + _strMasterPKName + " ";
                SqlCommand sqlComUpMaster = new SqlCommand(strSQLUpMaster, sqlConn);
                sqlComUpMaster.Parameters.Add("@" + _strMasterPKName, SqlDbType.VarChar, 100);
                sqlComUpMaster.Parameters["@" + _strMasterPKName].Value = strPKValue;
                sqlComUpMaster.Transaction = tran;
                sqlComUpMaster.ExecuteNonQuery();
                //清除消息
                string strSQLDelMsg = "DELETE T_Message WHERE ModuleName = '" + _strModuleName + "' AND PKCode = '" + _strMasterPKValue + "'";
                SqlCommand sqlComDelMessage = new SqlCommand(strSQLDelMsg, sqlConn);
                sqlComDelMessage.Transaction = tran;
                sqlComDelMessage.ExecuteNonQuery();
                //发送消息
                if (strNoticUserCode.EndsWith("|"))
                {
                    strNoticUserCode = strNoticUserCode.Substring(0, strNoticUserCode.Length - 1);
                }
                if (strStatus ==100)
                {
                    string strMsgText = strCreaterName + "的"+_strModuleName+"[" + strPKValue + "]已审批通过！";
                    string strSQLSendMsg = "INSERT INTO T_Message(Sender,Receiver,SendDates,ISRead,MessageText,ModuleName,PKCode,PriorID) VALUES('" + strUserCode + "','" + strNoticUserCode + "',GetDate(),0,'"
                        + strMsgText + "','" + _strModuleName + "','" + _strMasterPKValue + "',-1)";
                    SqlCommand sqlComSendMsg = new SqlCommand(strSQLSendMsg, sqlConn);
                    sqlComSendMsg.Transaction = tran;
                    sqlComSendMsg.ExecuteNonQuery();
                }
                else if (strStatus ==10)
                {
                    string strMsgText = strCreaterName + "的" + _strModuleName + "[" + _strMasterPKValue + "]需要你的签字！";
                    string[] toupleNoticeUserList = strNoticUserCode.Split('|');
                    for (int i = 0; i < toupleNoticeUserList.Length; i++)
                    {
                        string strSQLSendMsg = "INSERT INTO T_Message(Sender,Receiver,SendDates,ISRead,MessageText,ModuleName,PKCode,PriorID) VALUES('" + strUserCode + "','" + toupleNoticeUserList[i] + "',GetDate(),0,'"
                        + strMsgText + "','" + _strModuleName + "','" + _strMasterPKValue + "',-1)";
                        SqlCommand sqlComSendMsg = new SqlCommand(strSQLSendMsg, sqlConn);
                        sqlComSendMsg.Transaction = tran;
                        sqlComSendMsg.ExecuteNonQuery();
                    }
                }
                #endregion

                tran.Commit();
                sqlConn.Close();
                return jsonResult = "{\"success\":true  ,\"data\":{\"result\":\"成功\"}   ,\"message\":\"\"}";
            }
            catch (Exception ex)
            {
                if (tran != null)
                    tran.Rollback();
                return jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        //审批未通过
        public string AuditNotPass(string strModuleName, string strPKValue, string strSortID, string strUserCode, string strAuditNote, string strSaveTime) 
        {
            string jsonResult = string.Empty;
            //模块名、主键字段、主键值、主表名、审批表名
            string _strModuleName = string.Empty;
            string _strMasterTableName = string.Empty;
            string _strAuditTableName = string.Empty;
            string _strMasterPKName = string.Empty;
            string _strMasterPKValue = string.Empty;
            //模块名、主键值
            _strModuleName = Microsoft.JScript.GlobalObject.decodeURIComponent(strModuleName);
            _strMasterPKValue = strPKValue;
            //取出对应的表名、审批表名、主键名
            switch (_strModuleName)
            {
                case "外销合同":
                    {
                        _strMasterTableName = "T_ExpPact";
                        _strAuditTableName = "T_ExpPactAudit";
                        _strMasterPKName = "PactNum";
                    }
                    break;
                case "销售报价":
                    {
                        _strMasterTableName = "T_ExpQuote";
                        _strAuditTableName = "T_ExpQuoteAudit";
                        _strMasterPKName = "QuoteNum";
                    }
                    break;
                case "采购合同":
                    {
                        _strMasterTableName = "T_StockPact";
                        _strMasterPKName = "PactNum";
                        _strAuditTableName = "T_StockPactAudit";
                    }
                    break;
                case "预付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付费用申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付货款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付佣金申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "其他付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "议付单证":
                    {
                        _strMasterTableName = "T_InvoiceDoc";
                        _strMasterPKName = "InvoiceNum";
                        _strAuditTableName = "T_InvoiceDocAudit";
                    }
                    break;
            }
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            sqlConn.Open();
            SqlTransaction tran =null;

            #region 验证时间戳、更新审批表、主表、删除消息、发送消息
            try
            {
                #region 验证时间戳

                string strSQLSaveTime = "select SaveTime From "+_strMasterTableName+" Where "+_strMasterPKName+"=@"+_strMasterPKName+" and isDel=0 ";
                SqlCommand sqlComSaveTime = new SqlCommand(strSQLSaveTime, sqlConn);
                sqlComSaveTime.Parameters.Add("@"+_strMasterPKName, SqlDbType.VarChar, 50);
                sqlComSaveTime.Parameters["@"+_strMasterPKName].Value = strPKValue;
                SqlDataAdapter sqlAdaSaveTime = new SqlDataAdapter(sqlComSaveTime);
                DataSet dsSaveTime = new DataSet();
                sqlAdaSaveTime.Fill(dsSaveTime);
                if (dsSaveTime.Tables[0].DefaultView.Count == 0)
                {
                    //记录已经不存在:直接Return 提示记录不存在.
                    return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"数据记录已经不存在!\"}";
                }
                //如果记录不存在：  情况是别人已删除                                （验证、中断提交、返回消息）
                //如果记录存在：但为空，                                            （不验证，继续）
                //如果记录存在：但不为空、此客户端为空：别人已保存过，              （验证、中断提交、返回消息）
                //如果记录存在：但不为空、此客户端不为空：相同：别人未保存          （验证、继续）
                //如果记录存在：但不为空、此客户端不为空：不同：别人保存过          （验证、中断提交、返回消息）

                string strTimeClient = string.Empty;
                string strTrueSaveTime = string.Empty;

                //如果数库记录存在：且为空。不验证、继续。
                //如果数库记录存在：不为空。1、客户端无时间戳、有时间戳不一致。均提示已修改。
                if (dsSaveTime.Tables[0].DefaultView[0]["SaveTime"] != DBNull.Value)
                {
                    //取出数据库中时间
                    DateTime dtTrueSaveTime = (DateTime)dsSaveTime.Tables[0].DefaultView[0]["SaveTime"];
                    strTrueSaveTime = string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", dtTrueSaveTime);

                    strSaveTime = Microsoft.JScript.GlobalObject.decodeURIComponent(strSaveTime);
                    if (strSaveTime == "null" || string.IsNullOrEmpty(strSaveTime) || strSaveTime != strTrueSaveTime)
                    {
                        //记录已经不存在:直接Return 提示记录不存在.
                        return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"记录已经被别人修改，请重新打开！\"}";
                    }
                }
                #endregion

                //注意按审批流程排序
                string strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,aa.SendAuditDate,bb.* FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                        + " LEFT JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "' ORDER BY bb.SortID ASC";
                string strTableName = "T_Audit";
                SqlDataAdapter sqlDA;
                DataSet dsAudit = new DataSet();

                sqlDA = new SqlDataAdapter(strSQL, sqlConn);
                sqlDA.Fill(dsAudit, strTableName);
                DataTable dtAudit = dsAudit.Tables[0];
                //创建者
                string strCreater = string.Empty;
                string strCreaterName = string.Empty;
                string strFlowName = string.Empty;
                if (dsAudit.Tables.Count > 0 && dsAudit.Tables[0].Rows.Count > 0)
                {
                    strCreater = dtAudit.Rows[0]["Creater"].ToString();
                    strCreaterName = dtAudit.Rows[0]["CreaterName"].ToString();
                    strFlowName = dtAudit.Rows[0]["FlowName"].ToString();
                }
                //未通过   审批表-1   主表3
                int stateAuditAuditState = -1;
                int stateMasterAuditState = 3;

                #region 审批处理的事务：更新审批表、主表、清除消息、发送消息
                tran = sqlConn.BeginTransaction();

                //更新审批表
                string strSQLUpAudit = "Update "+_strAuditTableName+" Set AuditState=@AuditState ,Auditer=@Auditer ,AuditDate=getdate(),AuditNote=@AuditNote where isDel=0 and "+_strMasterPKName+"=@"+_strMasterPKName+" and SortID=@SortID";
                SqlCommand sqlComUpAduit = new SqlCommand(strSQLUpAudit, sqlConn);
                //类型、长度、名称
                sqlComUpAduit.Parameters.Add("@AuditState", SqlDbType.Int);
                sqlComUpAduit.Parameters["@AuditState"].Value = stateAuditAuditState;
                sqlComUpAduit.Parameters.Add("@Auditer", SqlDbType.VarChar, 50);
                sqlComUpAduit.Parameters["@Auditer"].Value = strUserCode;
                sqlComUpAduit.Parameters.Add("@AuditNote", SqlDbType.Text);
                sqlComUpAduit.Parameters["@AuditNote"].Value = strAuditNote.Trim();
                sqlComUpAduit.Parameters.Add("@"+_strMasterPKName, SqlDbType.VarChar,100);
                sqlComUpAduit.Parameters["@"+_strMasterPKName].Value = strPKValue;
                sqlComUpAduit.Parameters.Add("@SortID", SqlDbType.Int);
                sqlComUpAduit.Parameters["@SortID"].Value = strSortID;
                sqlComUpAduit.Transaction = tran;
                sqlComUpAduit.ExecuteNonQuery();
                //更新主表
                string strSQLUpMaster = "Update "+_strMasterTableName+" set SaveTime=getDate(),AuditState=" + stateMasterAuditState + "where isDel=0 and "+_strMasterPKName+"='" + _strMasterPKValue + "'";
                SqlCommand sqlComUpMaster = new SqlCommand(strSQLUpMaster, sqlConn);
                sqlComUpMaster.Transaction = tran;
                sqlComUpMaster.ExecuteNonQuery();
                //删除消息
                string strSQLDelMsg = "DELETE T_Message WHERE ModuleName = '" + _strModuleName + "' AND PKCode = '" + _strMasterPKValue + "'";
                SqlCommand sqlComDelMessage = new SqlCommand(strSQLDelMsg, sqlConn);
                sqlComDelMessage.Transaction = tran;
                sqlComDelMessage.ExecuteNonQuery();
                //发送消息
                if (strCreater.EndsWith("|"))
                {
                    strCreater = strCreater.Substring(0, strCreater.Length - 1);
                }
                string strMsgText = strCreaterName + "的"+_strModuleName+"[" + strPKValue + "]审批未通过！";
                string strSQLSendMsg = "INSERT INTO T_Message(Sender,Receiver,SendDates,ISRead,MessageText,ModuleName,PKCode,PriorID) VALUES('" + strUserCode + "','" + strCreater + "',GetDate(),0,'"
                    + strMsgText + "','" + _strModuleName + "','" + _strMasterPKValue + "',-1)";
                SqlCommand sqlComSendMsg = new SqlCommand(strSQLSendMsg, sqlConn);
                sqlComSendMsg.Transaction = tran;
                sqlComSendMsg.ExecuteNonQuery();
                
                #endregion

                tran.Commit();
                sqlConn.Close();
                return jsonResult = "{\"success\":true  ,\"data\":{\"result\":\"成功\"}   ,\"message\":\"\"}";
            }
            catch (Exception ex)
            {
                if (tran != null)
                    tran.Rollback();
                return jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
            #endregion
        }
        //待审批                
        public string AuditWait(string strModuleName, string strPKValue, string strSortID, string strUserCode, string strAuditNote,string strSaveTime)
        {
            string jsonResult = string.Empty;
            //模块名、主键字段、主键值、主表名、审批表名
            string _strModuleName = string.Empty;
            string _strMasterTableName = string.Empty;
            string _strAuditTableName = string.Empty;
            string _strMasterPKName = string.Empty;
            string _strMasterPKValue = string.Empty;
            //模块名、主键值
            _strModuleName = Microsoft.JScript.GlobalObject.decodeURIComponent(strModuleName);
            _strMasterPKValue = strPKValue;

            //取出对应的表名、审批表名、主键名
            switch (_strModuleName)
            {
                case "外销合同":
                    {
                        _strMasterTableName = "T_ExpPact";
                        _strAuditTableName = "T_ExpPactAudit";
                        _strMasterPKName = "PactNum";
                    }
                    break;
                case "销售报价":
                    {
                        _strMasterTableName = "T_ExpQuote";
                        _strAuditTableName = "T_ExpQuoteAudit";
                        _strMasterPKName = "QuoteNum";
                    }
                    break;
                case "采购合同":
                    {
                        _strMasterTableName = "T_StockPact";
                        _strMasterPKName = "PactNum";
                        _strAuditTableName = "T_StockPactAudit";
                    }
                    break;
                case "预付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付费用申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付货款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "付佣金申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "其他付款申请":
                    {
                        _strMasterTableName = "T_ApplyMoney";
                        _strMasterPKName = "ApplyNum";
                        _strAuditTableName = "T_ApplyMoneyAudit";
                    }
                    break;
                case "议付单证":
                    {
                        _strMasterTableName = "T_InvoiceDoc";
                        _strMasterPKName = "InvoiceNum";
                        _strAuditTableName = "T_InvoiceDocAudit";
                    }
                    break;
            }
            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            sqlConn.Open();
            SqlTransaction tran =null;
            try
            {
                #region 验证时间戳
		 
                string strSQLSaveTime = "select SaveTime From "+_strMasterTableName+" Where "+_strMasterPKName+"=@"+_strMasterPKName+" and isDel=0 ";
                SqlCommand sqlComSaveTime = new SqlCommand(strSQLSaveTime, sqlConn);
                sqlComSaveTime.Parameters.Add("@" + _strMasterPKName, SqlDbType.VarChar, 50);
                sqlComSaveTime.Parameters["@" + _strMasterPKName].Value = _strMasterPKValue;
                SqlDataAdapter sqlAdaSaveTime = new SqlDataAdapter(sqlComSaveTime);
                DataSet dsSaveTime = new DataSet();
                sqlAdaSaveTime.Fill(dsSaveTime);
                if (dsSaveTime.Tables[0].DefaultView.Count == 0)
                {
                    //记录已经不存在:直接Return 提示记录不存在.
                    return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"数据记录已经不存在!\"}";
                }
                //如果记录不存在：  情况是别人已删除                                （验证、中断提交、返回消息）
                //如果记录存在：但为空，                                            （不验证，继续）
                //如果记录存在：但不为空、此客户端为空：别人已保存过，              （验证、中断提交、返回消息）
                //如果记录存在：但不为空、此客户端不为空：相同：别人未保存          （验证、继续）
                //如果记录存在：但不为空、此客户端不为空：不同：别人保存过          （验证、中断提交、返回消息）

                string strTimeClient = string.Empty;
                string strTrueSaveTime = string.Empty;

                //如果数库记录存在：且为空。不验证、继续。
                //如果数库记录存在：不为空。1、客户端无时间戳、有时间戳不一致。均提示已修改。
                if (dsSaveTime.Tables[0].DefaultView[0]["SaveTime"] != DBNull.Value)
                {
                    //取出数据库中时间
                    DateTime dtTrueSaveTime = (DateTime)dsSaveTime.Tables[0].DefaultView[0]["SaveTime"];
                    strTrueSaveTime = string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", dtTrueSaveTime);

                    strSaveTime = Microsoft.JScript.GlobalObject.decodeURIComponent(strSaveTime);
                    if (strSaveTime == "null" || string.IsNullOrEmpty(strSaveTime) || strSaveTime != strTrueSaveTime)
                    {
                        //记录已经不存在:直接Return 提示记录不存在.
                        return jsonResult = "{\"success\":true  ,\"data\":{}   ,\"message\":\"记录已经被别人修改，请重新打开！\"}";
                    }
                }
                #endregion

                //注意按审批流程排序
                string strSQL = "SELECT aa.Creater,aa.CreaterName,aa.AuditState AS MasterAuditState,aa.SendAuditState,aa.SendAuditDate,bb.*  FROM (SELECT * FROM " + _strMasterTableName + " WHERE isdel=0) aa  "
                        + " LEFT JOIN (SELECT * FROM " + _strAuditTableName + " WHERE isdel=0) bb  ON aa." + _strMasterPKName + "=bb." + _strMasterPKName + " WHERE aa." + _strMasterPKName + "='" + _strMasterPKValue + "' ORDER BY bb.SortID ASC";
                string strTableName = "T_Audit";
                SqlDataAdapter sqlDA;
                DataSet dsAudit = new DataSet();
                sqlDA = new SqlDataAdapter(strSQL, sqlConn);
                sqlDA.Fill(dsAudit, strTableName);
                DataTable dtAudit = dsAudit.Tables[0];
                //创建者
                string strCreater = string.Empty;
                string strCreaterName = string.Empty;
                string strFlowName = string.Empty;
                if (dsAudit.Tables.Count > 0 && dsAudit.Tables[0].Rows.Count > 0)
                {
                    strCreater = dtAudit.Rows[0]["Creater"].ToString();
                    strCreaterName = dtAudit.Rows[0]["CreaterName"].ToString();
                    strFlowName = dtAudit.Rows[0]["FlowName"].ToString();
                }
                //待签（取消）    主表0    审批表0；
                int stateAuditAuditState = 0;
                int stateMasterAuditState = 0;


                #region 审批处理的事务：更新审批表、主表、清除消息、发送消息
                tran = sqlConn.BeginTransaction();

                //更新审批表
                string strSQLUpAudit = "Update "+_strAuditTableName+" Set AuditState=@AuditState ,Auditer='' ,AuditDate=null,AuditNote=@AuditNote where isDel=0 and "+_strMasterPKName+"=@"+_strMasterPKName+" and SortID=@SortID";
                SqlCommand sqlComUpAduit = new SqlCommand(strSQLUpAudit, sqlConn);
                sqlComUpAduit.Parameters.Add("@AuditState", SqlDbType.Int);
                sqlComUpAduit.Parameters["@AuditState"].Value = stateAuditAuditState;
                sqlComUpAduit.Parameters.Add("@AuditNote", SqlDbType.Text);
                sqlComUpAduit.Parameters["@AuditNote"].Value = strAuditNote.Trim();
                sqlComUpAduit.Parameters.Add("@"+_strMasterPKName, SqlDbType.VarChar, 100);
                sqlComUpAduit.Parameters["@" + _strMasterPKName].Value = strPKValue;
                sqlComUpAduit.Parameters.Add("@SortID", SqlDbType.Int);
                sqlComUpAduit.Parameters["@SortID"].Value = strSortID;
                sqlComUpAduit.Transaction = tran;
                sqlComUpAduit.ExecuteNonQuery();
                //更新主表
                string strSQLUpMaster = "Update "+_strMasterTableName+" set SaveTime=GETDATE(),AuditState=" + stateMasterAuditState + "where isDel=0 and "+_strMasterPKName+"='" + _strMasterPKValue + "'";
                SqlCommand sqlComUpMaster = new SqlCommand(strSQLUpMaster, sqlConn);
                sqlComUpMaster.Transaction = tran;
                sqlComUpMaster.ExecuteNonQuery();
                //清除消息
                string strSQLDelMsg = "DELETE T_Message WHERE ModuleName = '" + _strModuleName + "' AND PKCode = '" + _strMasterPKValue + "'";
                SqlCommand sqlComDelMessage = new SqlCommand(strSQLDelMsg, sqlConn);
                sqlComDelMessage.Transaction = tran;
                sqlComDelMessage.ExecuteNonQuery();
                
                #endregion

                tran.Commit();
                sqlConn.Close();
                return jsonResult = "{\"success\":true  ,\"data\":{\"result\":\"成功\"}   ,\"message\":\"\"}";
            }
            catch (Exception ex)
            {
                if (tran != null)
                    tran.Rollback();
                return jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
        //打印模板                      [修改处：Case模块名、主键名]
        public string DownReportFile(string strModuleName,string strPKValue,string strRptGUID, string strRptName, string strUserCode)
        {
            string jsonResult = string.Empty;

            //取到模块名、主表名、主键名、主键值
            string _strModuleName = Microsoft.JScript.GlobalObject.decodeURIComponent(strModuleName);
            string _strRptName = Microsoft.JScript.GlobalObject.decodeURIComponent(strRptName);
            string _strMasterPKValue = strPKValue;

            string _strMasterTableName = string.Empty;
            string _strMasterPKName = string.Empty;

            string strReportSQL = string.Empty;
            string strSQLGroup1 = string.Empty;
            string strSQLGroup2 = string.Empty;
            string strColumnGroup1 = string.Empty;
            string strColumnGroup2 = string.Empty;
            int iMaxRow = 30;
            int iMaxCol = 30;
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
            SqlConnection sqlConn = new SqlConnection(strConnString);


            string strSQL = string.Empty;
            string strWhere = string.Empty;
            SqlDataAdapter sqlAda;
            DataSet dsReport = new DataSet();
            try
            {
                sqlConn.Open();

                #region 确定主键名称，不同的模块，不同的主键名称；

                if (_strModuleName == "外销合同")
                {
                    _strMasterPKName = "PactNum";
                }
                else if (_strModuleName == "销售报价")
                {
                    _strMasterPKName = "QuoteNum";
                }
                else if (_strModuleName == "采购合同")
                {
                    _strMasterPKName = "PactNum";
                }
                else if (_strModuleName == "预付款申请")
                {
                    _strMasterPKName = "ApplyNum";
                }
                else if (_strModuleName == "付费用申请")
                {
                    _strMasterPKName = "ApplyNum";
                }
                else if (_strModuleName == "付货款申请")
                {
                    _strMasterPKName = "ApplyNum";
                }
                else if (_strModuleName == "付佣金申请")
                {
                    _strMasterPKName = "ApplyNum";
                }
                else if (_strModuleName == "其他付款申请")
                {
                    _strMasterPKName = "ApplyNum";
                }
                else if (_strModuleName == "议付单证")
                {
                    _strMasterPKName = "InvoiceNum";
                }
                #endregion

                strSQL = "SELECT ModuleName,RptClass,RptName,ReportSQL,ReportParam,Remark,SQLGroup1,SQLGroup2,ColumnGroup1,ColumnGroup2,MaxRow,MaxCol,AllowReader,ISSignView FROM ts_Report where ISDel=0 AND ModuleName='" + _strModuleName + "' and RptClass='Excel' and RptName='" + _strRptName + "'";
                strWhere = " WHERE 1 = 1 And isDel=0 and " + _strMasterPKName + "='" + _strMasterPKValue + "'";

                sqlAda = new SqlDataAdapter(strSQL, sqlConn);
                sqlAda.Fill(dsReport,"Report");

                if (dsReport.Tables[0].DefaultView.Count > 0)
                {
                    strReportSQL = dsReport.Tables[0].DefaultView[0]["ReportSQL"].ToString().ToUpper().Replace("[SQLWHERE]", strWhere);
                    strReportSQL = strReportSQL.Replace("[UserCode]".ToUpper(), "'" + strUserCode + "'");
                    strSQLGroup1 = dsReport.Tables[0].DefaultView[0]["SQLGroup1"].ToString().ToUpper().Replace("[SQLWHERE]", strWhere);
                    strSQLGroup2 = dsReport.Tables[0].DefaultView[0]["SQLGroup2"].ToString().ToUpper().Replace("[SQLWHERE]", strWhere);
                    strColumnGroup1 = dsReport.Tables[0].DefaultView[0]["ColumnGroup1"].ToString();
                    strColumnGroup2 = dsReport.Tables[0].DefaultView[0]["ColumnGroup2"].ToString();
                    iMaxRow = dsReport.Tables[0].DefaultView[0]["MaxRow"] == DBNull.Value ? 0 : (int)dsReport.Tables[0].DefaultView[0]["MaxRow"];
                    iMaxCol = dsReport.Tables[0].DefaultView[0]["MaxCol"] == DBNull.Value ? 0 : (int)dsReport.Tables[0].DefaultView[0]["MaxCol"];
                }
                //保存路径
                string strFileNamePath = Server.MapPath("/ftp/AppDown");
                strFileNamePath = strFileNamePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                //每次的保存名称，都用GUID。防止占用。
                string strTempFile = System.Guid.NewGuid()+ ".xlsx";

                string strExcelFileName = strFileNamePath + "\\" + strTempFile;
                //如果文件夹不存在，创建该文件夹
                if (!Directory.Exists(strFileNamePath))
                {
                    Directory.CreateDirectory(strFileNamePath);
                }
                //核心方法－数据填充Excel然后保存到指定的服务器路径
                new Trade.DBUtility.XLSReportClass().PrintExcel(iMaxRow, iMaxCol,_strModuleName, _strRptName, strReportSQL, strSQLGroup1, strSQLGroup2, strColumnGroup1, strColumnGroup2, strExcelFileName, strConnString);
                sqlConn.Close();
                //生成图片的网络路径
                string strHttpServerAddress = ConfigurationManager.AppSettings["HttpServerAddress"].ToString();
                string strHttpServerPort = ConfigurationManager.AppSettings["HttpServerPort"].ToString();
                string strWebPath = strHttpServerAddress + ":" + strHttpServerPort;
                string strWebFilePath = strWebPath + "/ftp/AppDown/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + strTempFile;
                return jsonResult = "{\"success\":true ,\"data\":{\"result\":\"成功\",\"FilePath\":\""+strWebFilePath+"\"}   ,\"message\":\"\"}";
            }
            catch (Exception ex)
            {
                return jsonResult = "{\"success\":false ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        } 

    }
}
